package org.odk.collect.android.widgets;



import org.javarosa.core.model.data.GeoPointData;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.activities.GeoPointActivity;
import org.odk.collect.android.views.QuestionView;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * GeocodetWidget is the widget that allows the user to get nearest intersection street names 
 * from GPS location. This widget was added to take care of geocoding needs for the PEQI.
 * 
 * @author Shilpa Vijayan (svijayan@ucla.edu)
 * 
 */
public class GeoCodeWidget extends LinearLayout implements IQuestionWidget, IBinaryWidget {

    private Button mActionButton;
    private TextView mStringAnswer;
    private TextView mAnswerDisplay;
    
    public GeoCodeWidget(Context context) {
        super(context);
    }


    public void clearAnswer() {
        mStringAnswer.setText(null);
        mAnswerDisplay.setText(null);
        mActionButton.setText(getContext().getString(R.string.get_location));

    }

    public IAnswerData getAnswer() {
        String s = mStringAnswer.getText().toString();
        if (s == null || s.equals("")) {
            return null;
        } else {
        	return new StringData(s);           
        }
    } 

    public void buildView(FormEntryPrompt prompt) {

        setOrientation(LinearLayout.VERTICAL);

        mActionButton = new Button(getContext());
        mActionButton.setPadding(20, 20, 20, 20);
        mActionButton.setText(getContext().getString(R.string.get_location));
        mActionButton.setTextSize(TypedValue.COMPLEX_UNIT_PX, QuestionView.APPLICATION_FONTSIZE);
        mActionButton.setEnabled(!prompt.isReadOnly());

        mStringAnswer = new TextView(getContext());

        mAnswerDisplay = new TextView(getContext());
        mAnswerDisplay.setTextSize(TypedValue.COMPLEX_UNIT_PX,
            QuestionView.APPLICATION_FONTSIZE - 1);
        mAnswerDisplay.setGravity(Gravity.CENTER);
                
        String s = prompt.getAnswerText();
        if (s != null && !s.equals("")) {
            mActionButton.setText(getContext().getString(R.string.replace_location));
            setBinaryData(s);
        }

        // when you press the button
        mActionButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent i = new Intent(getContext(), GeoPointActivity.class);
                i.putExtra(GeoPointActivity.GEOCODE, "true");
                ((Activity) getContext()).startActivityForResult(i,
                    FormEntryActivity.LOCATION_GEOCODE_CAPTURE);

            }
        });

        // finish complex layout
        addView(mActionButton);
        addView(mAnswerDisplay);
    }


    private String formatGps(double coordinates, String type) {
        String location = Double.toString(coordinates);
        String degreeSign = "\u00B0";
        String degree = location.substring(0, location.indexOf(".")) + degreeSign;
        location = "0." + location.substring(location.indexOf(".") + 1);
        double temp = Double.valueOf(location) * 60;
        location = Double.toString(temp);
        String mins = location.substring(0, location.indexOf(".")) + "'";

        location = "0." + location.substring(location.indexOf(".") + 1);
        temp = Double.valueOf(location) * 60;
        location = Double.toString(temp);
        String secs = location.substring(0, location.indexOf(".")) + '"';
        if (type.equalsIgnoreCase("lon")) {
            if (degree.startsWith("-")) {
                degree = "W " + degree.replace("-", "") + mins + secs;
            } else
                degree = "E " + degree.replace("-", "") + mins + secs;
        } else {
            if (degree.startsWith("-")) {
                degree = "S " + degree.replace("-", "") + mins + secs;
            } else
                degree = "N " + degree.replace("-", "") + mins + secs;
        }
        return degree;
    }


    public void setFocus(Context context) {
        // Hide the soft keyboard if it's showing.
        InputMethodManager inputManager =
            (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
    }


    public void setBinaryData(Object answer) {
        String s = (String) answer;
        mStringAnswer.setText(s);
        
        String[] sa = s.split(" ");    
        String si = "";
        for(int i=4;i<sa.length;i++){
        	si = si + " " + sa[i];
        }
                       
        mAnswerDisplay.setText(getContext().getString(R.string.latitude) + ": "
                + formatGps(Double.parseDouble(sa[0]), "lat") + "\n"
                + getContext().getString(R.string.longitude) + ": "
                + formatGps(Double.parseDouble(sa[1]), "lon") + "\n"
                + getContext().getString(R.string.altitude) + ": " + sa[2] + "\n"
                + getContext().getString(R.string.accuracy) + ": " + sa[3] + "m\n"
                + getContext().getString(R.string.intersection) + ": " + si);
    }
        

}
